<?php

namespace app\home\controller;

use think\Lang;


/**
 * ============================================================================
 * DSMall多用户商城
 * ============================================================================
 * 版权所有 2014-2028 长沙德尚网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.csdeshang.com
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * 控制器
 */
class Sellergoodsadd extends BaseSeller
{
    public function _initialize()
    {
        parent::_initialize();
        error_reporting(E_ERROR | E_WARNING);
        Lang::load(APP_PATH . 'home/lang/' . config('default_lang') . '/sellergoodsadd.lang.php');
    }

    /**
     * 三方店铺验证，商品数量，有效期
     */
    private function checkStore()
    {
        $goodsLimit = (int)$this->store_grade['storegrade_goods_limit'];
        if ($goodsLimit > 0) {
            // 是否到达商品数上限
            $goods_num = model('goods')->getGoodsCommonCount(array('store_id' => session('store_id')));
            if ($goods_num >= $goodsLimit) {
                $this->error(lang('store_goods_index_goods_limit') . $goodsLimit . lang('store_goods_index_goods_limit1'), url('Sellergoodsonline/goods_list'));
            }
        }
    }

    public function index()
    {

        // $this->checkStore();
        $this->add_step_one();
    }

    /**
     * 添加商品
     */
    public function add_step_one()
    {

        // 实例化商品分类模型
        $goodsclass_model = model('goodsclass');
        // 商品分类
        $goods_class = $goodsclass_model->getGoodsclass(session('store_id'));
        //halt($goods_class);

        // 常用商品分类
        $staple_model = model('goodsclassstaple');
        $param_array = array();
        $param_array['member_id'] = session('member_id');
        $staple_array = $staple_model->getGoodsclassstapleList($param_array);

        $this->assign('staple_array', $staple_array);
        $this->assign('goods_class', $goods_class);
        /* 设置卖家当前菜单 */
        $this->setSellerCurMenu('sellergoodsadd');
        $this->setSellerCurItem();
        echo $this->fetch($this->template_dir . 'store_goods_add_step1');
        exit;
    }

    /**
     * 添加商品
     */
    public function add_step_two()
    {

        // 实例化商品分类模型
        $goodsclass_model = model('goodsclass');
        // 现暂时改为从匿名“自营店铺专属等级”中判断
        $editor_multimedia = false;
        if ($this->store_grade['storegrade_function'] == 'editor_multimedia') {
            $editor_multimedia = true;
        }
        $this->assign('editor_multimedia', $editor_multimedia);

        $gc_id = intval(input('get.class_id'));

        // 验证商品分类是否存在且商品分类是否为最后一级
        $data = model('goodsclass')->getGoodsclassForCacheModel();
        if (!isset($data[$gc_id]) || isset($data[$gc_id]['child']) || isset($data[$gc_id]['childchild'])) {
            $this->error(lang('store_goods_index_again_choose_category1'));
        }

        // 如果不是自营店铺或者自营店铺未绑定全部商品类目，读取绑定分类
        if (!check_platform_store_bindingall_goodsclass()) {
            //商品分类  支持批量显示分类
            $storebindclass_model = model('storebindclass');
            $goods_class = model('goodsclass')->getGoodsclassForCacheModel();
            $where['store_id'] = session('store_id');
            $class_2 = isset($goods_class[$gc_id]['gc_parent_id']) ? $goods_class[$gc_id]['gc_parent_id'] : 0;
            $class_1 = isset($goods_class[$class_2]['gc_parent_id']) ? $goods_class[$class_2]['gc_parent_id'] : 0;
            $where['class_1'] = ($class_1 > 0) ? $class_1 : (($class_2 > 0) ? $class_2 : $gc_id);
            $where['class_2'] = ($class_1 > 0) ? $class_2 : (($class_2 > 0) ? $gc_id : 0);
            $where['class_3'] = ($class_1 > 0 && $class_2 > 0) ? $gc_id : 0;
            $bind_info = $storebindclass_model->getStorebindclassInfo($where);
            if (empty($bind_info)) {
                $where['class_3'] = 0;
                $bind_info = $storebindclass_model->getStorebindclassInfo($where);
                if (empty($bind_info)) {
                    $where['class_2'] = 0;
                    $where['class_3'] = 0;
                    $bind_info = $storebindclass_model->getStorebindclassInfo($where);
                    if (empty($bind_info)) {
                        $where['class_1'] = 0;
                        $where['class_2'] = 0;
                        $where['class_3'] = 0;
                        $bind_info = model('storebindclass')->getStorebindclassInfo($where);
                        /* if (empty($bind_info)) {
                             $this->error(lang('store_goods_index_again_choose_category2'));
                         }*/
                    }
                }
            }
        }

        // 更新常用分类信息
        $goods_class = $goodsclass_model->getGoodsclassLineForTag($gc_id);
        $this->assign('goods_class', $goods_class);
        model('goodsclassstaple')->autoIncrementStaple($goods_class, session('member_id'));

        // 获取类型相关数据
        $typeinfo = model('type')->getAttribute($goods_class['type_id'], session('store_id'), $gc_id);
        list($spec_json, $spec_list, $attr_list, $brand_list) = $typeinfo;
        $this->assign('sign_i', count($spec_list));
        $this->assign('spec_list', $spec_list);
        $this->assign('attr_list', $attr_list);
        $this->assign('brand_list', $brand_list);

        // 实例化店铺商品分类模型
        $store_goods_class = model('storegoodsclass')
            ->getClassTree(
                array(
                    'store_id' => session('store_id'),
                    'storegc_state' => '1'
                )
            );
        $this->assign('store_goods_class', $store_goods_class);

        /*//商品顶级类别
        $goods_type = db('goods_category')->where(['status'=>0])->where('pid','<>','0')->select();
        $ids = array_unique(array_column($goods_type, 'pid'));

        $goods_types = db('goods_category')->where('id','in',$ids)->select();
        $this->assign('goods_type', $goods_types);*/

        // 小时分钟显示
        $hour_array = array(
            '00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17',
            '18', '19', '20', '21', '22', '23'
        );
        $this->assign('hour_array', $hour_array);
        $minute_array = array('05', '10', '15', '20', '25', '30', '35', '40', '45', '50', '55');
        $this->assign('minute_array', $minute_array);

        // 关联版式
        $plate_list = model('storeplate')->getStoreplateList(array('store_id' => session('store_id')), 'storeplate_id,storeplate_name,storeplate_position');
        $plate_list = array_under_reset($plate_list, 'storeplate_position', 2);
        $this->assign('plate_list', $plate_list);
        /* 设置卖家当前菜单 */
        $this->setSellerCurMenu('sellergoodsadd');
        $this->setSellerCurItem();
        return $this->fetch($this->template_dir . 'store_goods_add_step2');
    }


    /**
     * 保存商品（商品发布第二步使用）
     */
    public function save_goods()
    {
        if (request()->isPost()) {
            #判断是否设置规格
            // p(input('post.'));die;
            if (empty(input('post.spec/a'))) {
                #如果没有设置规格
                // if (empty(input('post.goods_marketprice'))) {
                //     return json(['url' => '', 'code' => -1, 'msg' => '请设置商品出厂价']);
                //     die;
                // }
                if (empty(input('post.goods_price'))) {
                    return json(['url' => '', 'code' => -1, 'msg' => '请设置商品出厂价格']);
                    die;
                }
                if (empty(input('post.goods_storage'))) {
                    return json(['url' => '', 'code' => -1, 'msg' => '请设置商品库存']);
                    die;
                }
                if (empty(input('post.goods_storage_alarm'))) {
                    return json(['url' => '', 'code' => -1, 'msg' => '请设置商品库存安全值']);
                    die;
                }
            }
            $goods_model = model('goods');
            $goods_model->startTrans();
            try {
                $type_model = model('type');

                // 分类信息
                $goods_class = model('goodsclass')->getGoodsclassLineForTag(intval(input('post.cate_id')));

                $common_array = array();
                #轮播图视频
                if (isset($_POST['videos']) && !empty($_POST['videos'])) {
                    $common_array['videos'] = $_POST['videos'];
                }

                $common_array['goods_name'] = input('post.g_name');
                $common_array['gc_id'] = intval(input('post.cate_id'));
                $common_array['gc_id_1'] = intval($goods_class['gc_id_1']);
                $common_array['gc_id_2'] = intval($goods_class['gc_id_2']);
                $common_array['gc_id_3'] = intval($goods_class['gc_id_3']);
                #设置库存
                $common_array['goods_storage_alarm'] = input('goods_storage_alarm');
                $common_array['goods_price'] = input('goods_price');
                // $common_array['goods_marketprice'] = input('goods_marketprice');

                $common_array['gc_name'] = input('post.cate_name');
                $common_array['brand_id'] = input('post.b_id');
                $common_array['brand_name'] = input('post.b_name');

                $attr_array = input('post.attr/a');#获取数组
                if (!empty($attr_array)) {
                    foreach ($attr_array as $attr_key => $attr_value) {
                        foreach ($attr_value as $temp) {
                            if ($temp == '') {
                                unset($attr_array[$attr_key]); //过滤掉没选择的属性
                            }
                        }
                    }
                    if (!empty($attr_array)) {
                        $attr = $attr_array;
                    } else {
                        $attr = null;
                    }
                } else {
                    $attr = null;
                }

                $common_array['goods_attr'] = serialize($attr);
                $common_array['goods_body'] = input('post.goods_body');
                $common_array['goods_state'] = 0;            // 店铺关闭时，商品下架
                $common_array['goods_addtime'] = TIMESTAMP;
                $common_array['goods_verify'] = 0;
                $common_array['store_id'] = session('store_id');
                $common_array['store_name'] = session('store_name');
                $common_array['spec_name'] = is_array(input('post.spec/a')) ? serialize(input('post.sp_name/a')) : serialize(null);
                $common_array['spec_value'] = is_array(input('post.spec/a')) ? serialize(input('post.sp_val/a')) : serialize(null);

                // 保存数据
                $common_id = $goods_model->addGoodsCommon($common_array);
                if ($common_id) {
                    // 生成的商品id（SKU）
                    $goodsid_array = array();
                    // 商品规格
                    $spec_array = input('post.spec/a');#获取数组
                    if (is_array($spec_array) && !empty($spec_array)) {
                        foreach($spec_array as $k=>$value){
                            if(!isset($value['sp_value'])){
                             unset($spec_array[$k]);
                            }
                        }
                        foreach ($spec_array as $value) {
                            $goods = array();
                            $goods['goods_commonid'] = $common_id;
                            $goods['goods_name'] = $common_array['goods_name'] . ' ' . implode(' ', $value['sp_value']);
                            $goods['spec_values'] = implode(';', $value['sp_value']);
                            $goods['store_id'] = $common_array['store_id'];
                            $goods['store_name'] = session('store_name');
                            $goods['gc_id'] = $common_array['gc_id'];
                            $goods['gc_id_1'] = $common_array['gc_id_1'];
                            $goods['gc_id_2'] = $common_array['gc_id_2'];
                            $goods['gc_id_3'] = $common_array['gc_id_3'];
                            $goods['brand_id'] = $common_array['brand_id'];
                            $goods['goods_price'] = $value['price'] == 0 || $value['price'] == '' ? 0 : $value['price'];
                            $goods['goods_promotion_price'] = $value['price'] == 0 || $value['price'] == '' ? 0 : $value['price'];
                            // $goods['goods_marketprice'] = $value['marketprice'] == 0 || $value['marketprice'] == '' ? 0 : $value['marketprice'];
                            $goods['goods_serial'] = $value['sku'] == '' ? 0 : $value['sku'];
                            $goods['goods_storage_alarm'] = intval($value['alarm']) == 0 || intval($value['alarm']) == '' ? 0 : intval($value['alarm']);
                            $goods['goods_spec'] = serialize($value['sp_value']);
                            $goods['goods_storage'] = $value['stock'] == 0 || $value['stock'] == '' ? 0 : $value['stock'];
                            $goods['goods_state'] = $common_array['goods_state'];
                            $goods['goods_verify'] = $common_array['goods_verify'];
                            $goods['goods_addtime'] = TIMESTAMP;
                            $goods['goods_edittime'] = TIMESTAMP;
                            $goods['color_id'] = isset($value['color']) ? intval($value['color']) : '';
                            $goods_id = $goods_model->addGoods($goods);
                            $type_model->addGoodsType($goods_id, $common_id, array(
                                'cate_id' => input('post.cate_id'), 'type_id' => input('post.type_id'), 'attr' => input('post.attr/a')
                            ));

                            $goodsid_array[] = $goods_id;
                        }
                    } else {
                        $goods = array();
                        $goods['goods_commonid'] = $common_id;
                        $goods['goods_name'] = $common_array['goods_name'];

                        $goods['store_id'] = $common_array['store_id'];
                        $goods['store_name'] = session('store_name');
                        $goods['gc_id'] = $common_array['gc_id'];
                        $goods['gc_id_1'] = $common_array['gc_id_1'];
                        $goods['gc_id_2'] = $common_array['gc_id_2'];
                        $goods['gc_id_3'] = $common_array['gc_id_3'];
                        $goods['brand_id'] = $common_array['brand_id'];
                        $goods['goods_spec'] = serialize(null);
                        $goods['goods_state'] = $common_array['goods_state'];
                        $goods['goods_verify'] = $common_array['goods_verify'];
                        $goods['goods_price'] = input('goods_price');
                        $goods['goods_storage'] = input('goods_storage');
                        // $goods['goods_marketprice'] = input('goods_marketprice');
                        $goods['goods_storage_alarm'] = input('goods_storage_alarm');
                        $goods['goods_addtime'] = TIMESTAMP;
                        $goods['goods_edittime'] = TIMESTAMP;
                        $goods_id = $goods_model->addGoods($goods);
                        $type_model->addGoodsType($goods_id, $common_id, array(
                            'cate_id' => input('post.cate_id'), 'type_id' => input('post.type_id'), 'attr' => input('post.attr/a')
                        ));

                        $goodsid_array[] = $goods_id;
                    }

                    // 记录日志
                    $this->recordSellerlog('添加商品，平台货号:' . $common_id);

                } else {
                    exception(lang('store_goods_index_goods_add_fail'));
                }

            } catch (\Exception $e) {
                $goods_model->rollback();
                $this->error($e->getMessage(), get_referer());
            }
            $goods_model->commit();
            if (input('add_type') == 1) {
                #下一步
                return json(['url' => url('Sellergoodsadd/perfect_goods', ['commonid' => $common_id]), 'code' => 1, 'msg' => '添加成功']);
                die;
            } else {
                #暂存信息
                return json(['url' => url('Sellergoodsinfomessage/perfect_goods_list'), 'code' => 1, 'msg' => '暂存成功']);
                die;
            }

        }
    }


    /**
     * 第三步完善商品信息
     */
    public function perfect_goods()
    {
        $common_id = input('param.commonid');
        if ($common_id <= 0) {
            $this->error(lang('wrong_argument'), url('Seller/index'));
        }
        /*查询goods商品*/
        $goods_info = db('goods')->where('goods_commonid', $common_id)->select();
        $this->assign('commonid', $common_id);

        $json_goods_info = json_encode($goods_info);
        $this->assign('goods_info', $goods_info);
        $this->assign('json_goods_info', $json_goods_info);

        $top_area = db('area')->where(['area_deep' => 1, 'area_parent_id' => 0])->select();
        foreach ($top_area as $k => $v) {
            $top_area[$k]['area_list'] = db('area')->where(['area_deep' => 2, 'area_parent_id' => $v['area_id']])->field('area_id')->select();
        }
        foreach ($top_area as $k => $v) {
            foreach ($v['area_list'] as $ke => $va) {
                $top_area[$k]['last_id'][] = db('area')->where(['area_deep' => 3, 'area_parent_id' => $va['area_id']])->field('areacode')->select();

            }
        }

        foreach ($top_area as $k => $v) {
            if (!isset($top_area[$k]['last_id'])) {
                $top_area[$k]['last_id'] = array();
            }
        }

        foreach ($top_area as $k => $v) {
            foreach ($v['last_id'] as $ke => $va) {
                foreach ($va as $key => $val) {
                    $top_area[$k]['last_id_info'][] = $val['areacode'];

                }
            }
            unset($top_area[$k]['last_id']);
            unset($top_area[$k]['area_list']);
        }

        foreach ($top_area as $k => $v) {
            if (isset($v['last_id_info'])) {
                $top_area[$k]['last_ids'] = implode(',', $v['last_id_info']);
            } else {
                $top_area[$k]['last_ids'] = $v['areacode'];
            }

        }
        $this->assign('top_area', $top_area);

        /* 设置卖家当前菜单 */
        $this->setSellerCurMenu('sellergoodsadd');
        $this->setSellerCurItem();
        return $this->fetch($this->template_dir . 'perfect_goods');
    }

    /**
     * 主商品详情页
     */
    public function store_goods_detail()
    {
        if (request()->isPost()) {
        } else {
            $store_id = session('store_id');
            $store_status = db('store')->where(['store_id' => $store_id])->find()['store_type'];
            $this->assign('store_status', $store_status);
            $config = db('config')->where('code', 'qiniu_http')->find();
            $this->assign('http_name', $config['value']);
            $commonid = input('param.commonid');
            $goods = db('y_goods')->where(['goods_commonid' => $commonid])->find();
            $this->view->goods = $goods;
            $this->assign('commonids', $commonid);
            $goods_info = db('goodscommon')->where(['goods_commonid' => $commonid])->find();

            $goods = db('goods')->where(['goods_commonid' => $commonid])->select();
            $this->assign('goods', $goods);
            if (empty($goods_info['files'])) {
                $goods_info['files_info'] = '';
            } else {
                $goods_info['files_info'] = json_decode($goods_info['files'], true);
                $goods_info['files_info']['old_file_name'] = explode(',', $goods_info['files_info']['old_file_name']);
                $goods_info['files_info']['new_file_name'] = explode(',', $goods_info['files_info']['new_file_name']);
            }
            //p($goods_info);die;
            //获取分类名称
            $name = db('goodsclass')->where(['gc_id' => $goods_info['gc_id_3']])->find();
            $name1 = db('goodsclass')->where(['gc_id' => $goods_info['gc_id_2']])->find();
            $name2 = db('goodsclass')->where(['gc_id' => $goods_info['gc_id_1']])->find();

            if (!empty($name2) && !empty($name1) && !empty($name)) {
                $goods_info['class_name'] = $name2['gc_name'] . '>' . $name1['gc_name'] . '>' . $name['gc_name'];
            } elseif (!empty($name2) && !empty($name1)) {
                $goods_info['class_name'] = $name2['gc_name'] . '>' . $name1['gc_name'];
            } else {
                $goods_info['class_name'] = $name2['gc_name'];
            }

            $this->assign('goods_info', $goods_info);

            $goods_img = db('goodsimages')->where(['goods_commonid' => $commonid])->select();
            $this->assign('goods_img', $goods_img);

            return $this->fetch($this->template_dir . 'store_goods_detail');
        }
    }


    /**
     * 子商品详情页
     */
    public function goods_setting_info()
    {
        if (request()->isPost()) {
        } else {
            $commonid = input('param.goods_id');
            $is_href = input('param.is_href');
            $goods = db('goods')->where(['goods_id' => $commonid])->find();
            $goods_info = db('goodscommon')->where(['goods_commonid' => $goods['goods_commonid']])->find();
            if (empty($goods['files'])) {
                $goods['files_info'] = '';
            } else {
                $goods['files_info'] = json_decode($goods['files'], true);
                $goods['files_info']['old_file_name'] = explode(',', $goods['files_info']['old_file_name']);
                $goods['files_info']['new_file_name'] = explode(',', $goods['files_info']['new_file_name']);
            }
            if ($is_href == '') {
                $goods['is_href'] = 0;

            } else {
                $goods['is_href'] = 1;
            }

            //获取运费模板
            $waybill_info = db('waybill')->where(['waybill_id' => $goods['waybill_id']])->find();

            $this->assign('goods', $goods);
            $this->assign('goods_info', $goods_info);
            $this->assign('waybill_info', $waybill_info);
            #质保期限 1--0，2--三个月， 3--六个月，4--一年 5-- 两年 6 -- 三年
            $this->assign('warranty_period_text',array('0'=>'未设置','1'=>'不包含','2'=>'三个月','3'=>'六个月','4'=>'一年','5'=>'两年','6'=>'三年'));
            $config = db('config')->where('code', 'qiniu_http')->find();
            $this->assign('http_name', $config['value']);
            return $this->fetch($this->template_dir . 'goods_setting_info');
        }
    }


    /**
     * 完善商品信息弹框
     */
    public function perfect_goods_content()
    {
        $common_id = input('param.commonid');

        if ($common_id <= 0) {
            $this->error(lang('wrong_argument'), url('Seller/index'));
        }
        //改变状态
        $tag = db('goods')->where(['goods_id' => $common_id])->find();
        db('goodscommon')->where(['goods_commonid' => $tag['goods_commonid']])->update(['goods_status' => -1]);
        if (!strpos($common_id, ',')) {
            $goods = db('goods')->where(['goods_id' => $common_id])->find();
            if (empty($goods['files'])) {
                $goods['files_info'] = '';
            } else {
                $goods['files_info'] = json_decode($goods['files'], true);
                $goods['files_info']['old_file_name'] = explode(',', $goods['files_info']['old_file_name']);
                $goods['files_info']['new_file_name'] = explode(',', $goods['files_info']['new_file_name']);
            }

            //  p($goods);die;
            $this->assign('goods_info', $goods);
        }
        $waybill_info = db('waybill')->where('status', '1')->where('store_id', session('store_id'))->order('sort', 'desc')->field('waybill_id,waybill_name')->select();
        $this->assign('waybill_info', $waybill_info);
        $this->assign('commonid', $common_id);
        //商品产地
        $area_model = model('area');
        $where = array();
        $where['area_parent_id'] = 0;
        $top_area_class = $area_model->getarea_list($where, 'area_id,area_name');
        if (empty($top_area_class)) {
            $this->error('暂无省份');
        }

        $this->assign('top_area_class', $top_area_class);

        /* 设置卖家当前菜单 */
        $this->setSellerCurMenu('sellergoodsadd');
        $this->setSellerCurItem();
        return $this->fetch($this->template_dir . 'perfect_goods_content');
    }


    /**
     * 完善商品信息弹框 添加&&编辑
     */
    public function perfect_goods_content_save()
    {
        $data = input('post.');
      //  p($data);die;
        $update_array = array();
        if (isset($_POST['files']) && !empty($_POST['files'])) {
            $file_info['new_file_name'] = implode(',', $_POST['files']);
            $file_info['old_file_name'] = implode(',', $_POST['old_files']);
            $update_array['files'] = json_encode($file_info);
        }
        $update_array['goods_code'] = $data['goods_code'];
        $update_array['goods_factory'] = $data['goods_factory'];
        $update_array['waybill_type'] = $data['waybill_type'];
        $update_array['hair_area_id1'] = $data['hair_area_id1'];
        $update_array['hair_area_id2'] = $data['hair_area_id2'];
        $update_array['area_id1'] = $data['area_id1'];
        $update_array['area_id2'] = $data['area_id2'];
        $update_array['waybill_id'] = $data['waybill_id'];
        $update_array['weight'] = $data['weight'];
        $update_array['volume'] = $data['volume'];
        $update_array['delivery_date'] = $data['delivery_date'];
        $update_array['packing'] = $data['packing'];
        $update_array['packing_long'] = $data['packing_long'];
        $update_array['packing_width'] = $data['packing_width'];
        $update_array['change_goods'] = $data['change_goods'];
        $update_array['return_goods'] = $data['return_goods'];
        $update_array['packing_high'] = $data['packing_high'];
        $update_array['goods_production'] = $data['goods_production'];
        $update_array['is_w_v'] = $data['is_w_v'];
        $update_array['warranty_period'] = $data['warranty_period'];

        $update_array['is_to_pay'] = $data['is_to_pay'];
        #商品产地
        $area1_info = db('area')->where(['area_id' => $data['area_id1']])->find();
        $area2_info = db('area')->where(['area_id' => $data['area_id2']])->find();
        $area_name = $area1_info['area_name'] . ',' . $area2_info['area_name'];
        $update_array['address'] = $area_name;

        #商品发货地
        $hair_area1_info = db('area')->where(['area_id' => $data['hair_area_id1']])->find();
        $hair_area2_info = db('area')->where(['area_id' => $data['hair_area_id2']])->find();
        $area_name = $hair_area1_info['area_name'] . ',' . $hair_area2_info['area_name'];
        $update_array['hair_address'] = $area_name;
        // p($update_array);die;
        if (strpos($data['commonids'], ',')) {
            #多个操作
            $ids = explode(',', $data['commonids']);
            foreach ($ids as $k => $v) {
                $res = db('goods')->where('goods_id', $v)->data($update_array)->update();
            }
        } else {
            #单个
            $where['goods_id'] = $data['commonids'];
            $res = db('goods')->where($where)->data($update_array)->update();
        }
        if ($res) {
            return json(['code' => 0]);
        } else {
            return json(['code' => 1]);
        }
    }

    /**
     * 设置销售区域弹框 添加&&编辑
     */
    public function save_area()
    {
        $data = input('post.');

        //改变状态
        // $tag = db('goods')->where(['goods_id'=>$data['ids'])->find();
        // db('goodscommon')->where(['goods_commonid'=>$tag['goods_commonid']])->update(['goods_status'=>-1]);

        $update_array = array();
        $update_array['area_name'] = implode(',', $data['area_name']);
        $update_array['area'] = implode(',', $data['area_ids']);
        if (strpos($data['ids'], ',')) {
            #多个操作
            $ids = explode(',', $data['ids']);
            foreach ($ids as $k => $v) {
                $res = db('goods')->where('goods_id', $v)->data($update_array)->update();
            }
        } else {
            #单个
            $where['goods_id'] = $data['ids'];
            $res = db('goods')->where($where)->data($update_array)->update();
        }
        if ($res) {
            return json(['code' => 0]);
        } else {
            return json(['code' => 1]);
        }
    }


    /**
     * 第四步设置商品图片
     */
    public function add_step_four()
    {

        $common_id = input('param.commonid');
        if ($common_id <= 0) {
            $this->error(lang('wrong_argument'), url('Seller/index'));
        }
        $file_http = db('config')->where('code', 'qiniu_http')->find();
        $this->assign('http_name', $file_http['value']);
        $goods_model = model('goods');
        $img_array = $goods_model->getGoodsList(array('goods_commonid' => $common_id), 'color_id,goods_image', 'color_id');
        // 整理，更具id查询颜色名称
        $colorid_array = array();
        if (!empty($img_array)) {
            $image_array = array();
            foreach ($img_array as $val) {
                $image_array[$val['color_id']][0]['goodsimage_url'] = $val['goods_image'];
                $image_array[$val['color_id']][0]['goodsimage_isdefault'] = 1;
                $colorid_array[] = $val['color_id'];
            }
            $this->assign('img', $image_array);
        }

        $common_list = $goods_model->getGoodeCommonInfoByID($common_id);
        $spec_value = unserialize($common_list['spec_value']);
        $this->assign('value', $spec_value['1']);

        $spec_model = model('spec');
        $value_array = $spec_model->getSpecvalueList(array('spvalue_id' => array('in', $colorid_array), 'store_id' => session('store_id')), 'spvalue_id,spvalue_name');
        if (empty($value_array)) {
            $value_array[] = array('spvalue_id' => '0', 'spvalue_name' => lang('no_color'));
        }
        $this->assign('value_array', $value_array);

        $this->assign('commonid', $common_id);


        /* 设置卖家当前菜单 */
        $this->setSellerCurMenu('sellergoodsadd');
        $this->setSellerCurItem();
        return $this->fetch($this->template_dir . 'store_goods_add_step3');
    }

    /**
     * 保存商品颜色图片
     */
    public function save_image()
    {
        if (request()->isPost()) {
            $common_id = intval(input('param.commonid'));
            // p($_POST);die;
            $img_array = input('post.img/a');#获取数组
            if ($common_id <= 0 || empty($img_array)) {
                $data = array();
                $data['msg'] = '参数错误，商品已放入草稿箱';
                $data['code'] = 0;
                return $data;
                $this->error(lang('wrong_argument'));
            }
            $goods_model = model('goods');

            // 保存
            $insert_array = array();
            $k = 0;
            foreach ($img_array as $key => $value) {
                foreach ($value as $v) {
                    if ($v['name'] == '') {
                        continue;
                    }
                    // 商品默认主图
                    $update_array = array();        // 更新商品主图
                    $update_where = array();
                    $update_array['goods_image'] = $v['name'];
                    $update_where['goods_commonid'] = $common_id;
                    $update_where['color_id'] = $key;
                    if ($k == 0 || $v['default'] == 1) {
                        $k++;
                        $update_array['goods_image'] = $v['name'];
                        $update_where['goods_commonid'] = $common_id;
                        $update_where['color_id'] = $key;
                        // 更新商品主图
                        if (input('add_type') == 1) {
                            db('goodscommon')->where('goods_commonid', $common_id)->data(['goods_image' => $v['name'], 'goods_status' => '0'])->update();
                        } else {
                            db('goodscommon')->where('goods_commonid', $common_id)->data(['goods_image' => $v['name']])->update();
                        }
                        $goods_model->editGoods($update_array, $update_where);
                    }
                    $tmp_insert = array();
                    $tmp_insert['goods_commonid'] = $common_id;
                    $tmp_insert['store_id'] = session('store_id');
                    $tmp_insert['color_id'] = $key;
                    $tmp_insert['goodsimage_url'] = $v['name'];
                    $tmp_insert['goodsimage_sort'] = ($v['default'] == 1) ? 0 : intval($v['sort']);
                    $tmp_insert['goodsimage_isdefault'] = $v['default'];
                    $insert_array[] = $tmp_insert;
                }
            }
            $rs = $goods_model->addGoodsImagesAll($insert_array);
            if (input('add_type') == 1) {
                #提交审核
                if ($rs) {
                    $data = array();
                    $data['url'] = url('sellergoodsinfomessage/goods_verify_list');
                    $data['code'] = 1;
                    return $data;
                } else {
                    $data = array();
                    $data['msg'] = '商品图片上传失败,商品已放入草稿箱';
                    $data['url'] = url('sellergoodsinfomessage/perfect_goods_list');
                    $data['code'] = 0;
                    return $data;
                }
            } else {
                #暂存
                if ($rs) {
                    $data = array();
                    $data['url'] = url('sellergoodsinfomessage/perfect_goods_list');
                    $data['code'] = 1;
                    return $data;
                } else {
                    $data = array();
                    $data['msg'] = '商品图片上传失败,商品已放入草稿箱';
                    $data['url'] = url('sellergoodsinfomessage/perfect_goods_list');
                    $data['code'] = 0;
                    return $data;

                }
            }

        }
    }

    /**
     * 商品发布第四步
     */
    public function add_step_fours()
    {
        $commonid = input('param.commonid');
        // 单条商品信息
        $goods_info = model('goods')->getGoodsInfo(array('goods_commonid' => $commonid));

        // 自动发布动态
        $data_array = array();
        $data_array['goods_id'] = $goods_info['goods_id'];
        $data_array['store_id'] = $goods_info['store_id'];
        $data_array['goods_name'] = $goods_info['goods_name'];
        $data_array['goods_image'] = $goods_info['goods_image'];
        $data_array['goods_price'] = $goods_info['goods_price'];
        $data_array['goods_transfee_charge'] = $goods_info['goods_freight'] == 0 ? 1 : 0;
        $data_array['goods_freight'] = $goods_info['goods_freight'];


        //自动发布店铺动态
        $this->storeAutoShare($data_array, 'new');

        $this->assign('allow_gift', model('goods')->checkGoodsIfAllowGift($goods_info));
        $this->assign('allow_combo', model('goods')->checkGoodsIfAllowCombo($goods_info));
        $this->assign('goods_id', $goods_info['goods_id']);

        /* 设置卖家当前菜单 */
        $this->setSellerCurMenu('sellergoodsadd');
        $this->setSellerCurItem();
        return $this->fetch($this->template_dir . 'store_goods_add_step4');
    }


    #主图
    public function image_upload()
    {

        $file_type = array('0' => 'jpg', '1' => 'jpeg', '2' => 'png');
        $file_name = input('post.name');
        $file_foot_name = substr($_FILES["$file_name"]['name'], (strripos($_FILES["$file_name"]['name'], ".")) + 1);
        if (!in_array($file_foot_name, $file_type)) {
            $error = '文件格式不对';
            exit(json_encode(array('error' => $error)));
            exit();
        }
        $file_name = input('post.name');
        $upload_info = upload_qiniu($file_name);
        //p($upload_info);die;
        $data['code'] = 1;
        $data['name'] = $upload_info['data'];
        $data['thumb_name'] = $upload_info['http'] . '/' . $upload_info['data'];


        // 存入相册
        $album_model = model('album');
        $insert_array = array();
        $insert_array['apic_name'] = $upload_info['http'] . '/' . $upload_info['data'];
        $insert_array['apic_tag'] = '';
        $insert_array['aclass_id'] = session('store_id');
        $insert_array['apic_cover'] = $upload_info['http'] . '/' . $upload_info['data'];
        $insert_array['apic_size'] = intval($_FILES[$file_name]['size']);
        $insert_array['apic_spec'] = '';
        $insert_array['apic_uploadtime'] = time();
        $insert_array['store_id'] = session('store_id');
        $result = model('album')->addAlbumpic($insert_array);
        echo json_encode($data);
        exit();
    }

    #说明书上传
    public function ajax_files()
    {
        $old_name = $_FILES['file']['name'];
        $file_type = array('0' => 'application/msword', '1' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', '2' => 'application/msword', '3' => 'application/vnd.ms-excel', '4' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', '5' => 'application/pdf');
        if (in_array($_FILES['file']['type'], $file_type)) {
            $upload_info = upload_qiniu('file');
            $data['msg'] = 1;
            $data['files_name'] = $upload_info['data'];
            $data['old_name'] = $old_name;
            return $data;
        } else {
            return $data['msg'] = 0;
        }
    }

    /**
     * Notes: 选择运费模板 ajax确定显示不显示到付
     * User: shen
     * Date: 2020/4/17
     * Time: 16:18
     * @return int
     */
    public function ajax_waybill()
    {
        $waybill_id = input('waybill_id', '');
        if ($waybill_id) {

            $waybill_info = db('waybill')->where('waybill_id', $waybill_id)->find();
            if ($waybill_info) {
                if ($waybill_info['is_bao'] == 1) {
                    $data['code'] = 1;
                    return $data;

                } else {
                    $data['code'] = 0;
                    return $data;
                }
            } else {
                $data['code'] = 0;
                return $data;
            }


        } else {
            $data['code'] = 0;
            return $data;
        }


    }

    #轮播图视频上传
    public function ajax_videos()
    {
        $old_name = $_FILES['file']['name'];
        $file_type = array('0' => 'mov', '1' => 'mp4', '2' => 'wmv', '3' => 'avi');
        $file_foot_name = substr($_FILES['file']['name'], (strripos($_FILES['file']['name'], ".")) + 1);
        if (!in_array($file_foot_name, $file_type)) {
            $data['msg'] = 1;
            return $data;
        }
        $upload_info = upload_qiniu('file');
        $data['msg'] = 1;
        $data['files_name'] = $upload_info['data'];
        return $data;
    }


    /**
     * ajax获取商品分类的子级数据
     */
    public function ajax_goods_class()
    {
        $gc_id = intval(input('get.gc_id'));
        $deep = intval(input('get.deep'));
        if ($gc_id <= 0 || $deep <= 0 || $deep >= 4) {
            exit(json_encode(array()));
        }
        $goodsclass_model = model('goodsclass');
        $list = $goodsclass_model->getGoodsclass(session('store_id'), $gc_id, $deep);
        if (empty($list)) {
            exit(json_encode(array()));
        }
        echo json_encode($list);
    }

    /**
     * ajax删除常用分类
     */
    public function ajax_stapledel()
    {
        $staple_id = intval(input('get.staple_id'));
        if ($staple_id < 1) {
            echo json_encode(array('done' => false, 'msg' => lang('wrong_argument')));
            die();
        }
        /**
         * 实例化模型
         */
        $staple_model = model('goodsclassstaple');

        $result = $staple_model->delGoodsclassstaple(array('staple_id' => $staple_id, 'member_id' => session('member_id')));
        if ($result) {
            echo json_encode(array(
                'done' => true
            ));
            die();
        } else {
            echo json_encode(array(
                'done' => false, 'msg' => ''
            ));
            die();
        }
    }


    /**
     * ajax 获取城市
     */
    public function ajax_area()
    {
        $choose_id = input('choose_id');
        $area_list = db('area')->where(['area_parent_id' => $choose_id])->select();

        foreach ($area_list as $k => $v) {
            $area_list[$k]['area_list'] = db('area')->where(['area_deep' => 3, 'area_parent_id' => $v['area_id']])->field('area_id')->select();
        }

        foreach ($area_list as $k => $v) {
            foreach ($v['area_list'] as $ke => $va) {
                $area_list[$k]['last_id_info'][] = $va['area_id'];

            }
            unset($area_list[$k]['area_list']);
        }

        foreach ($area_list as $k => $v) {
            if (isset($v['last_id_info'])) {
                $area_list[$k]['last_ids'] = implode(',', $v['last_id_info']);
            } else {
                $area_list[$k]['last_ids'] = $v['area_id'];
            }

        }
        $area_info = db('area')->where(['area_id' => $choose_id])->find();
        if ($area_info['area_parent_id'] == 0) {

            foreach ($area_list as $k => $v) {
                if (isset($v['last_id_info'])) {
                    $area_list[$k]['last_ids'] = implode(',', $v['last_id_info']);
                    $area_list[$k]['top_name'] = $area_info['area_name'];
                } else {
                    $area_list[$k]['last_ids'] = $v['area_id'];
                    $area_list[$k]['top_name'] = $area_info['area_name'];
                }

            }
        } else {
            $area_infos = db('area')->where(['area_id' => $area_info['area_parent_id']])->find();
            foreach ($area_list as $k => $v) {
                if (isset($v['last_id_info'])) {
                    $area_list[$k]['last_ids'] = implode(',', $v['last_id_info']);
                    $area_list[$k]['top_name'] = $area_infos['area_name'];
                } else {
                    $area_list[$k]['last_ids'] = $v['area_id'];
                    $area_list[$k]['top_name'] = $area_infos['area_name'];
                }

            }
        }
        return $area_list;
    }


    /**
     * ajax选择常用商品分类
     */
    public function ajax_show_comm()
    {
        $staple_id = intval(input('get.stapleid'));

        /**
         * 查询相应的商品分类id
         */
        $staple_model = model('goodsclassstaple');
        $staple_info = $staple_model->getGoodsclassstapleInfo(array('staple_id' => intval($staple_id)), 'gc_id_1,gc_id_2,gc_id_3');
        if (empty($staple_info) || !is_array($staple_info)) {
            echo json_encode(array(
                'done' => false, 'msg' => ''
            ));
            die();
        }

        $list_array = array();
        $list_array['gc_id'] = 0;
        $list_array['type_id'] = $staple_info['type_id'];
        $list_array['done'] = true;
        $list_array['one'] = '';
        $list_array['two'] = '';
        $list_array['three'] = '';

        $gc_id_1 = intval($staple_info['gc_id_1']);
        $gc_id_2 = intval($staple_info['gc_id_2']);
        $gc_id_3 = intval($staple_info['gc_id_3']);

        /**
         * 查询同级分类列表
         */
        $goodsclass_model = model('goodsclass');
        // 1级
        if ($gc_id_1 > 0) {
            $list_array['gc_id'] = $gc_id_1;
            $class_list = $goodsclass_model->getGoodsclass(session('store_id'));
            if (empty($class_list) || !is_array($class_list)) {
                echo json_encode(array('done' => false, 'msg' => ''));
                die();
            }
            foreach ($class_list as $val) {
                if ($val ['gc_id'] == $gc_id_1) {
                    $list_array ['one'] .= '<li class="" onclick="selClass($(this));" data-param="{gcid:' . $val ['gc_id'] . ', deep:1, tid:' . $val ['type_id'] . '}" dstype="selClass"> <a class="classDivClick" href="javascript:void(0)"><span class="has_leaf"><i class="iconfont"></i>' . $val ['gc_name'] . '</span></a> </li>';
                } else {
                    $list_array ['one'] .= '<li class="" onclick="selClass($(this));" data-param="{gcid:' . $val ['gc_id'] . ', deep:1, tid:' . $val ['type_id'] . '}" dstype="selClass"> <a class="" href="javascript:void(0)"><span class="has_leaf"><i class="iconfont"></i>' . $val ['gc_name'] . '</span></a> </li>';
                }
            }
        }
        // 2级
        if ($gc_id_2 > 0) {
            $list_array['gc_id'] = $gc_id_2;
            $class_list = $goodsclass_model->getGoodsclass(session('store_id'), $gc_id_1, 2);
            if (empty($class_list) || !is_array($class_list)) {
                echo json_encode(array(
                    'done' => false, 'msg' => ''
                ));
                die();
            }
            foreach ($class_list as $val) {
                if ($val ['gc_id'] == $gc_id_2) {
                    $list_array ['two'] .= '<li class="" onclick="selClass($(this));" data-param="{gcid:' . $val ['gc_id'] . ', deep:2, tid:' . $val ['type_id'] . '}" dstype="selClass"> <a class="classDivClick" href="javascript:void(0)"><span class="has_leaf"><i class="iconfont"></i>' . $val ['gc_name'] . '</span></a> </li>';
                } else {
                    $list_array ['two'] .= '<li class="" onclick="selClass($(this));" data-param="{gcid:' . $val ['gc_id'] . ', deep:2, tid:' . $val ['type_id'] . '}" dstype="selClass"> <a class="" href="javascript:void(0)"><span class="has_leaf"><i class="iconfont"></i>' . $val ['gc_name'] . '</span></a> </li>';
                }
            }
        }
        // 3级
        if ($gc_id_3 > 0) {
            $list_array['gc_id'] = $gc_id_3;
            $class_list = $goodsclass_model->getGoodsclass(session('store_id'), $gc_id_2, 3);
            if (empty($class_list) || !is_array($class_list)) {
                echo json_encode(array(
                    'done' => false, 'msg' => ''
                ));
                die();
            }
            foreach ($class_list as $val) {
                if ($val ['gc_id'] == $gc_id_3) {
                    $list_array ['three'] .= '<li class="" onclick="selClass($(this));" data-param="{gcid:' . $val ['gc_id'] . ', deep:3, tid:' . $val ['type_id'] . '}" dstype="selClass"> <a class="classDivClick" href="javascript:void(0)"><span class="has_leaf"><i class="iconfont"></i>' . $val ['gc_name'] . '</span></a> </li>';
                } else {
                    $list_array ['three'] .= '<li class="" onclick="selClass($(this));" data-param="{gcid:' . $val ['gc_id'] . ', deep:3, tid:' . $val ['type_id'] . '}" dstype="selClass"> <a class="" href="javascript:void(0)"><span class="has_leaf"><i class="iconfont"></i>' . $val ['gc_name'] . '</span></a> </li>';
                }
            }
        }
        echo json_encode($list_array);
        die();
    }

    /**
     * AJAX添加商品规格值
     */
    public function ajax_add_spec()
    {
        $name = trim(input('get.name'));
        $gc_id = intval(input('get.gc_id'));
        $sp_id = intval(input('get.sp_id'));
        if ($name == '' || $gc_id <= 0 || $sp_id <= 0) {
            echo json_encode(array('done' => false));
            die();
        }
        $insert = array(
            'spvalue_name' => $name, 'sp_id' => $sp_id, 'gc_id' => $gc_id, 'store_id' => session('store_id'),
            'spvalue_color' => null, 'spvalue_sort' => 0,
        );
        $value_id = model('spec')->addSpecvalue($insert);
        if ($value_id) {
            echo json_encode(array('done' => true, 'value_id' => $value_id));
            die();
        } else {
            echo json_encode(array('done' => false));
            die();
        }
    }

    /**
     * AJAX查询品牌
     */
    public function ajax_get_brand()
    {
        $type_id = intval(input('tid'));
        $initial = trim(input('letter'));
        $keyword = trim(input('keyword'));
        $type = trim(input('type'));
        if (!in_array($type, array(
                'letter', 'keyword'
            )) || ($type == 'letter' && empty($initial)) || ($type == 'keyword' && empty($keyword))) {
            echo json_encode(array());
            die();
        }

        // 实例化模型
        $type_model = model('type');
        $where = array();
        $where['type_id'] = $type_id;
        // 验证类型是否关联品牌
        $count = $type_model->getTypebrandCount($where);
        if ($type == 'letter') {
            switch ($initial) {
                case 'all':
                    break;
                case '0-9':
                    $where['brand_initial'] = array('in', array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9));
                    break;
                default:
                    $where['brand_initial'] = $initial;
                    break;
            }
        } else {
            $where['brand_name|brand_initial'] = array('like', '%' . $keyword . '%');
        }
        if ($count > 0) {
            $brand_array = $type_model->typeRelatedJoinList($where, 'brand', 'brand.brand_id,brand.brand_name,brand.brand_initial');
        } else {
            unset($where['type_id']);
            $brand_array = model('brand')->getBrandPassedList($where, 'brand_id,brand_name,brand_initial', 0, 'brand_initial asc, brand_sort asc');
        }
        echo json_encode($brand_array);
        die();
    }


    /**
     * AJAx 获取地区
     */
    public function ajax_get_area_class()
    {
        if (request()->isAjax()) {
            $area_model = model('area');
            $area_id = trim(input('area_id'));
            #获取手机顶级分类
            $where = array();
            $where['area_parent_id'] = $area_id;
            $field = '';
            $field = 'area_id,area_name';
            $area_class = $area_model->getarea_list($where, $field);
            return $area_class;
        } else {
            $this->error('访问错误');
        }

    }

}

?>
